package top.xtcoder.jdcbase.base.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Arrays;

import org.apache.commons.codec.digest.DigestUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.FileUtil;
import net.coobird.thumbnailator.Thumbnails;
import top.xtcoder.jdcbase.base.common.Funs;
import top.xtcoder.jdcbase.base.config.FileUploadConf;
import top.xtcoder.jdcbase.base.entity.base.MimeType;
import top.xtcoder.jdcbase.base.entity.system.FileInfo;

@Service
public class UploadService {
	@Autowired
	private FileUploadConf fileUploadConf;
	
	@Autowired
	private Dao dao;
	
	/**
	 * 上传文件并保存到数据库
	 * @param file
	 * @param originalFilename
	 * @param title
	 * @return
	 * @throws Exception
	 */
	public FileInfo uploadAndSaveDB(File file, 
		String originalFilename, 
		String title,
		String contentType) throws Exception {
		FileInfo data = upload(file, originalFilename, title, contentType);
		data = dao.insertOrUpdate(data);
		return data;
	}
	
	private String getSuffix(String contentType, String filePath) {
		String suffix = "";
		if(Strings.isNotBlank(contentType)) {
			Cnd cnd = Cnd.where("isdelete", "=", 0);
			cnd.and("content_type", "=", contentType);
			MimeType type = dao.fetch(MimeType.class, cnd);
			if(type != null) {
				suffix = type.getSuffix();
			}
		}
		if(Strings.isBlank(suffix)) {
			suffix = Funs.getFileSuffix(filePath);
		}
		return suffix;
	}
	
	/**
	 * 文件上传
	 * @param file
	 * @param originalFilename
	 * @param title
	 * @return 
	 * @throws Exception
	 */
	public FileInfo upload(File file, 
		String originalFilename, 
		String title,
		String contentType) throws Exception {
		String dir = fileUploadConf.getSavePath();
		System.out.println("dir=" + dir);
		
		//检查目录写权限
		File fileBaseDir = new File(dir);
		if(!fileBaseDir.canWrite()){
			throw new Exception("上传目录没有写权限。");
		}
		String ymd = Funs.getNowLocalDate();
		String fileSuffix = getSuffix(contentType, file.getAbsolutePath());
		String fileName = Funs.getFileNameBySm3() + fileSuffix;
		String saveDirPath= File.separator + ymd;
		String saveFilePath = saveDirPath + File.separator + fileName;
		File saveDir = new File(dir, saveDirPath);
		if(!saveDir.exists()) {
			saveDir.mkdirs();
			File f = new File(saveDirPath, "index.html");
			f.createNewFile();
		}
		
		File saveFile = new File(dir, saveFilePath);
		//上传
		FileUtil.copy(file, saveFile, true);
		
		String url = fileUploadConf.getBaseUrl() + saveFilePath.replace(File.separator, "/");
		FileInfo data =new FileInfo();
		data.init();
		data.setName(originalFilename);
		data.setTitle(title);
		data.setContentType(contentType);
		data.setPath(saveFile.getAbsolutePath());
		data.setFileMd5(DigestUtils.md5Hex(new FileInputStream(saveFile)));
		data.setUrl(url);
		data.setSuffix(fileSuffix);
		data.setSize(saveFile.length());
		String userid = "DEFAULT";
		String usertype = "DEFAULT";
		try {
			userid = StpUtil.getLoginId().toString().substring(1);
			usertype=StpUtil.getLoginId().toString().substring(0,1);
		}catch(Exception e) {
			System.err.println("未登录用户上传，采用默认userid=DEFAULT");
		}
		data.setUserid(userid);
		return data;
	}
	
	/**
	 * 压缩文件
	 * @param file 待处理文件
	 * @param saveFile 处理后保存的文件
	 * @param scale 压缩比
	 */
	public void compress(File file,File saveFile,double scale) {
		try {
			Thumbnails.of(file).scale(scale).toFile(saveFile.getPath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 压缩文件
	 * @param file 待处理文件
	 * @param saveFile 处理后保存的文件
	 * @param scale 压缩比
	 */
	public void compress(InputStream is,File saveFile,double scale) {
		try {
			Thumbnails.of(is).scale(scale).toFile(saveFile.getPath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
}
